﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
using System.Text;
using QTMusic.BaseClasses;

namespace QTMusic.UserControls
{
    public partial class UploadSong : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            HttpCookie cookie = Request.Cookies["QTCookie"];
            if (!(cookie != null && cookie["Name"] != null && cookie["ID"] != null))
            {
                Response.Redirect("~/Default.aspx");
            }
            if (!IsPostBack)
            {
                LstShareOption.Items.Add(new ListItem("public", "2"));
                LstShareOption.Items.Add(new ListItem("friend", "1"));
                LstShareOption.Items.Add(new ListItem("private", "0"));
            }
        }

        protected void BtnUploadAndShare_click(Object sender, EventArgs e)
        {
            BtnUpload_click(sender, e);
            //Get current user
            HttpCookie cookie = Request.Cookies["QTCookie"];
            if (!(cookie != null && cookie["Name"] != null && cookie["ID"] != null))
                Response.Redirect("~/Websites/Default.aspx");

            //Get newly uploaded song
            SqlConnection conn = new SqlConnection(Common.connString);
            SqlCommand sql = new SqlCommand("SELECT max(song_id) AS last_id FROM [song]", conn);

            conn.Open();
            SqlDataReader reader = sql.ExecuteReader();
            reader.Read();
            int newlyInsertedSongId = (int)reader["last_id"];
            conn.Close();

            Response.Redirect("~/Websites/Profile.aspx?id=" + cookie["ID"] + "&SongId=" + newlyInsertedSongId.ToString());
        }

        protected void BtnUpload_click(Object sender, EventArgs e)
        {
            // Check that all controls are valid
            if (!Page.IsValid)
            {
                LblUploadInform.Text = "Some fields are invalid.";
                return;
            }

            // Check that a file is actually being submitted. 
            if (!AsyncFileUpload1.HasFile)
            {
                LblUploadInform.Text = "No file specified.";
                return;
            }

            // Check the extension. 
            string extension = Path.GetExtension(AsyncFileUpload1.FileName);

            switch (extension.ToLower())
            {
                case ".mp3":
                case ".wav":
                    break;
                default:
                    LblUploadInform.Text = "This file type is not allowed.";
                    return;
            }

            // add a random number to prevent duplicate file name
            Random rand = new Random(1000);

            string serverFileName = Path.GetFileName(AsyncFileUpload1.FileName);
            string randomizeServerFileName = InputSongname.Text + "[QT" + rand.Next().ToString() + "]" + Path.GetExtension(serverFileName);
            string uploadDirectory = Path.Combine(Request.PhysicalApplicationPath, @"MusicStorage\");
            string fullUploadPath = Path.Combine(uploadDirectory, randomizeServerFileName);

            try
            {
                AsyncFileUpload1.SaveAs(fullUploadPath);
                LblUploadInform.Text = "File uploaded successfully!";
            }
            catch (Exception err)
            {
                LblUploadInform.Text = err.Message;
                return;
            }

            //Upload file success, now insert new song
            // first find the artist ID that have the name specified, or if there are no matches, insert new artist
            // same work for Composer and Genre
            int ArtistID = -1;
            int GenreID = -1;
            int ComposerID = -1;
            int AlbumID = -1;
            int bitrate = 0;
            string length;

            ArtistID = GetExternLinkId("artist", InputArtist.Text, 0);
            GenreID = GetExternLinkId("genre", InputGenre.Text, 0);
            ComposerID = GetExternLinkId("composer", InputComposer.Text, 0);
            AlbumID = GetExternLinkId("album", InputAlbum.Text, ArtistID);
            song.GetMediaInfo(uploadDirectory, randomizeServerFileName, out bitrate, out length);


            SqlConnection conn = new SqlConnection(Common.connString);
            // Then insert new song record
            SqlCommand sql = new SqlCommand("INSERT INTO [song] (song_name, artist_id, genre_id, composer_id, album_id, song_release_date, song_length, song_bitrate, song_path, song_play_count, song_download_count, song_description, song_like_count, song_permission) VALUES (@name, @artistID, @genreID, @composerID, NULL, @releasedate, @Length, @bitrate, @songfile, 0, 0,  @description, 0, @permission)", conn);

            sql.Parameters.AddWithValue("@name", InputSongname.Text);
            sql.Parameters.AddWithValue("@artistID", ArtistID);
            if (GenreID != -1)
                sql.Parameters.AddWithValue("@genreID", GenreID);
            else
                sql.Parameters.AddWithValue("@genreID", DBNull.Value);
            if (ComposerID != -1)
                sql.Parameters.AddWithValue("@composerID", ComposerID);
            else
                sql.Parameters.AddWithValue("@composerID", DBNull.Value);
            if (AlbumID != -1)
                sql.Parameters.AddWithValue("@albumID", AlbumID);
            else
                sql.Parameters.AddWithValue("@albumID", DBNull.Value);
            if (InputReleaseDate.Text != "")
                sql.Parameters.AddWithValue("@releasedate", InputReleaseDate.Text);
            else
                sql.Parameters.AddWithValue("@releasedate", DBNull.Value);
            sql.Parameters.AddWithValue("@Length", length);
            sql.Parameters.AddWithValue("@bitrate", bitrate);
            sql.Parameters.AddWithValue("@songfile", randomizeServerFileName);
            if (InputDescription.Text != "")
                sql.Parameters.AddWithValue("@description", InputDescription.Text);
            else
                sql.Parameters.AddWithValue("@description", DBNull.Value);
            sql.Parameters.AddWithValue("@permission", int.Parse(LstShareOption.SelectedValue));

            conn.Open();
            int result = sql.ExecuteNonQuery();
            conn.Close();

            if (result != 0)
            {
                LblUploadInform.Text = "inserted";

                //add entry to songup and activity table

                //Get current user
                HttpCookie cookie = Request.Cookies["QTCookie"];
                if (!(cookie != null && cookie["Name"] != null && cookie["ID"] != null))
                    Response.Redirect("~/Websites/Default.aspx");

                int temp;
                int CurrentUserId = 0;
                if (int.TryParse(cookie["ID"], out temp))
                    CurrentUserId = temp;
                string CurrentTime = DateTime.Now.ToString();

                //select newly inserted songid
                sql = new SqlCommand("SELECT max(song_id) AS last_id FROM [song]", conn);

                conn.Open();
                SqlDataReader reader = sql.ExecuteReader();
                reader.Read();
                int newlyInsertedSongId = (int)reader["last_id"];
                conn.Close();

                sql = new SqlCommand("INSERT INTO [songup] (song_id, user_id, songup_time) VALUES (@song_id, @user_id, @songup_time)", conn);

                sql.Parameters.AddWithValue("@user_id", CurrentUserId);
                sql.Parameters.AddWithValue("@song_id", newlyInsertedSongId);
                sql.Parameters.AddWithValue("@songup_time", CurrentTime);

                conn.Open();
                result = sql.ExecuteNonQuery();
                conn.Close();

                if (result != 0)
                {
                    LblUploadInform.Text = "inserted 2";

                    sql = new SqlCommand("INSERT INTO [activity] (user_id, song_up_id, permission, time) VALUES (@user_id, @song_up_id, @permission, @share_time)", conn);

                    sql.Parameters.AddWithValue("@user_id", CurrentUserId);
                    sql.Parameters.AddWithValue("@song_up_id", newlyInsertedSongId);
                    sql.Parameters.AddWithValue("@permission", int.Parse(LstShareOption.SelectedValue));
                    sql.Parameters.AddWithValue("@share_time", CurrentTime);

                    conn.Open();
                    result = sql.ExecuteNonQuery();
                    conn.Close();

                    if (result != 0)
                        LblUploadInform.Text = "success";
                    else
                        LblUploadInform.Text = "failed";
                }
                else
                {
                    LblUploadInform.Text = "not inserted";
                }
            }
            else
            {
                LblUploadInform.Text = "failed";
            }
        }

        protected int GetExternLinkId(string target, string txtvalue, int additionalParam)
        {
            int ID = 0;
            StringBuilder selectCmd = new StringBuilder();
            StringBuilder insertCmd = new StringBuilder();

            if (txtvalue == "")
                return -1;
            selectCmd.AppendFormat("SELECT {0}_id FROM [{0}] WHERE {0}_name = @Target", target);
            insertCmd.AppendFormat("INSERT INTO [{0}]({0}_name) VALUES (@Target)", target);

            SqlConnection conn = new SqlConnection(Common.connString);
            SqlCommand sql_getid = new SqlCommand(selectCmd.ToString(), conn);
            sql_getid.Parameters.AddWithValue("@Target", txtvalue);

            conn.Open();
            SqlDataReader dataReader = sql_getid.ExecuteReader();


            if (dataReader.HasRows)
            {
                dataReader.Read();
                ID = (int)dataReader[0]; //first column is the id
                dataReader.Close();
            }
            else
            {
                dataReader.Close();
                if (target == "album")
                {
                    sql_getid = new SqlCommand("INSERT INTO [album](album_name, artist_id, album_song_count, album_play_count, album_like_count) VALUES(@albumname, @artistid, 0, 0, 0)", conn);
                    sql_getid.Parameters.AddWithValue("@albumname", txtvalue);
                    sql_getid.Parameters.AddWithValue("@artistId", additionalParam);

                }
                else 
                {
                    sql_getid = new SqlCommand(insertCmd.ToString(), conn);
                    sql_getid.Parameters.AddWithValue("@Target", txtvalue);
                }

                //them entry moi vao trong csdl
                int Result = sql_getid.ExecuteNonQuery();

                if (Result != 0)
                {
                    sql_getid = new SqlCommand(selectCmd.ToString(), conn);
                    sql_getid.Parameters.AddWithValue("@Target", txtvalue);

                    dataReader = sql_getid.ExecuteReader();

                    if (dataReader.Read())
                        ID = (int)dataReader[0];
                    dataReader.Close();
                }
            }
            conn.Close();

            return ID;
        }
    }
}